<template>
  <div style="flex-grow: 1; padding: 20px;">
    <el-row type="flex" justify="space-between" align="middle" style="margin-bottom: 20px;">
      <el-col>
        <h3>账户管理</h3>
      </el-col>
    </el-row>

    <el-table :data="users" style="width: 100%" stripe>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status ? 'success' : 'danger'">{{ scope.row.status ? '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="320">
        <template slot-scope="scope">
          <div style="display: flex; gap: 10px;">
            <el-button size="mini" @click="toggleStatus(scope.row)">切换状态</el-button>
            <el-button size="mini" @click="showChangePasswordDialog(scope.row)">修改密码</el-button>
            <el-button size="mini" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>

          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改密码的弹窗 -->
    <el-dialog
      title="修改密码"
      :visible.sync="changePasswordDialogVisible"
      width="400px"
      @close="resetPasswordForm"
    >
      <el-form :model="passwordForm" ref="passwordForm" label-width="100px">
        <el-form-item label="新密码" :rules="passwordRules.password">
          <el-input v-model="passwordForm.password" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changePasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPasswordChange">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import axios from 'axios';

export default {
  name: 'ManageAccountsView',
  data() {
    return {
      users: [],
      changePasswordDialogVisible: false,
      passwordForm: {
        password: '',
      },
      passwordRules: {
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符之间', trigger: 'blur' },
        ],
      },
      currentUser: null,
    };
  },
  computed: {
    ...mapState({
      isAdmin: state => state.userInfo.isAdmin,
    }),
  },
  mounted() {
    this.fetchUsers();
  },
  methods: {
    // 获取用户列表
    async fetchUsers() {
      try {
        const token = sessionStorage.getItem('jwt_token');
        if (!token) {
          this.$message.error('请先登录');
          return;
        }

        const response = await axios.get('http://localhost:5000/admin/users', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        this.users = response.data.users;
      } catch (error) {
        this.$message.error('获取用户列表失败');
      }
    },

    // 切换用户状态
    async toggleStatus(user) {
      try {
        await axios.patch(
          `http://localhost:5000/admin/update_user_status/${user.id}`,
          {},
          {
            headers: {
              Authorization: `Bearer ${sessionStorage.getItem('jwt_token')}`,
            },
          }
        );
        if(user.status){
          this.$message.error(`用户状态已更新为禁用`);

        }else{
          this.$message.success(`用户状态已更新为启用`);
        }
        this.fetchUsers();  // 刷新用户列表
      } catch (error) {
        this.$message.error('更新用户状态失败');
      }
    },

    // 删除用户
    async deleteUser(userId) {
      try {
        await axios.delete(`http://localhost:5000/admin/delete_user/${userId}`, {
          headers: {
            Authorization: `Bearer ${sessionStorage.getItem('jwt_token')}`,
          },
        });
        this.$message.success('用户已删除');
        this.fetchUsers();  // 刷新用户列表
      } catch (error) {
        this.$message.error('删除用户失败');
      }
    },

    // 显示修改密码弹窗
    showChangePasswordDialog(user) {
      this.currentUser = user;
      this.changePasswordDialogVisible = true;
    },

    // 重置密码表单
    resetPasswordForm() {
      this.passwordForm.password = '';
    },

    // 提交修改密码请求
    async submitPasswordChange() {
      try {
        this.$refs.passwordForm.validate(async (valid) => {
          if (valid) {
            await axios.patch(
              `http://localhost:5000/admin/update_password/${this.currentUser.id}`,
              { new_password: this.passwordForm.password },
              {
                headers: {
                  Authorization: `Bearer ${sessionStorage.getItem('jwt_token')}`,
                },
              }
            );
            this.$message.success('密码修改成功');
            this.changePasswordDialogVisible = false;
            await this.fetchUsers();  // 刷新用户列表
          }
        });
      } catch (error) {
        this.$message.error('修改密码失败');
      }
    },
  },
};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
</style>
